<template>
  <div>
    <ea-dialog
        v-bind="$attrs"
        v-on="$listeners"
        width="900px"
        ref="elDialog"
        :title="title"
        :type="type"
        @submit="submit"
        @reset="$refs.form.resetFields()"
        @closed="onClosed"
        :steps="steps"
        class="dialog"
        :step.sync="step"
        @check-step-field="checkFields"
    >
      <el-scrollbar wrap-class="scroll-wrap-y">
        <el-form
            ref="form"
            label-position="left"
            :model="singleData"
            :rules="rules"
            label-width="110px"
        >
          <!--    step 1-->
          <div class="step" v-show="step === 0">
            <el-form-item label="试卷名称" prop="papername">
              <el-input
                  v-model="singleData.papername"
                  placeholder="请输入试卷名"
              ></el-input>
            </el-form-item>
            <el-form-item label="试卷类型" prop="papertype">
              <el-select
                  v-model="singleData.papertype"
                  clearable
                  placeholder="请选择试卷类型"
              >
                <el-option
                    v-for="item in paperType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="有效时间" prop="selectTime">
              <el-date-picker
                  v-model="singleData.selectTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="是否私有" prop="isprivate">
              <el-radio-group v-model="singleData.isprivate">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="试卷状态" prop="isenabled">
              <el-radio-group v-model="singleData.isenabled">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <!--    step 2-->
          <div class="step" v-show="step === 1">
            <el-form-item label="选择题库" prop="quebanklist">
              <el-select
                  v-model="singleData.quebanklist"
                  @change="onQueBankChange"
                  clearable
                  multiple
                  collapse-tags
                  placeholder="请选择题库"
              >
                <el-option
                    v-for="item in queBanks"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择科目" prop="sublist">
              <el-select
                  v-model="singleData.sublist"
                  @change="onSubjectChange"
                  @clear="singleData.subquedetails.splice(0)"
                  clearable
                  collapse-tags
                  multiple
                  placeholder="请选择科目"
              >
                <el-option
                    v-for="item in subjects"
                    :key="item.subid"
                    :label="item.name"
                    :value="JSON.stringify(item)"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分值">
              <p class="danger">单选、多选、判断分值比例为1:2:1</p>
            </el-form-item>
            <el-tabs
                v-show="singleData.sublist"
                v-model="singleData.israndom"
                type="card"
            >
              <el-tab-pane label="固定试题" name="false">
                <el-form-item class="el-form-item-inline" label="单选题">
                  <el-button @click="onSelectQue(1)">选择题目</el-button>
                  <p>已选{{ singleData.singlequelist.length }}题</p>
                </el-form-item>
                <el-form-item
                    class="el-form-item-inline"
                    label="多选题"
                    prop="multiplechoicescore"
                >
                  <el-button @click="onSelectQue(2)">选择题目</el-button>
                  <p>已选{{ singleData.multiplequelist.length }}题</p>
                </el-form-item>
                <el-form-item
                    class="el-form-item-inline"
                    label="判断选题"
                    prop="truefalsescore"
                >
                  <el-button @click="onSelectQue(3)">选择题目</el-button>
                  <p>已选{{ singleData.truefalsequelist.length }}题</p>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="随机试题" name="true">
                <el-form-item label="选择章节" prop="chapteridlist">
                  <el-select
                      v-model="singleData.chapteridlist"
                      multiple
                      collapse-tags
                      filterable
                      placeholder="请选择"
                  >
                    <el-option-group
                        v-for="item in chapters"
                        :key="item.groupValue"
                        :label="item.groupName"
                    >
                      <el-option
                          v-for="i in item.keyValVOS"
                          :key="i.value"
                          :label="i.name"
                          :value="i.value"
                      >
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
                <el-form-item label="试卷是否相同">
                  <el-switch
                      v-model="singleData.isstusame"
                      :active-value="true"
                      :inactive-value="false"
                  />
                  <p class="danger">
                    注：该选项如果关闭，参与考试的每位学生的试卷均不相同
                  </p>
                </el-form-item>
                <div
                    class="random-que-setting"
                    v-for="item in singleData.subquedetails"
                    :key="'queDetail' + item.SubId"
                >
                  <el-divider content-position="left"
                  >{{ getSubName(item.SubId) }}
                  </el-divider>
                  <el-form-item
                      class="el-form-item-inline"
                      size="small"
                      label="题目分配"
                  >
                    <el-input v-model.number="item.SingleChoiceCount">
                      <template v-slot:prepend>单选</template>
                      <template v-slot:append>道</template>
                    </el-input>
                    <el-input v-model.number="item.MultipleChoiceCount">
                      <template v-slot:prepend>多选</template>
                      <template v-slot:append>道</template>
                    </el-input>
                    <el-input v-model.number="item.TrueFalseCount">
                      <template v-slot:prepend>判断</template>
                      <template v-slot:append>道</template>
                    </el-input>
                  </el-form-item>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
          <!--    step 3  -->
          <div class="step" v-show="step === 2">
            <el-form-item
                v-for="standard in singleData.scorestandard"
                :key="standard.Standard"
                :label="standard.Standard"
            >
              <el-input-number
                  v-model="standard.StartScore"
                  :controls="false"
              ></el-input-number>
              至
              <el-input-number
                  v-model="standard.EndScore"
                  :controls="false"
              ></el-input-number>
            </el-form-item>
          </div>
        </el-form>
      </el-scrollbar>
    </ea-dialog>
    <select-que
        ref="selectQue"
        :show.sync="showSelectQueDialog"
        @add-que="addQue"
    />
  </div>
</template>

<script>
import editAndAdd from "../../../mixins/business/editAndAdd";
import paperType from "../../../staticData/paperType";
import SelectQue from "./SelectQue";

export default {
  name: "EaPaper",
  components: {SelectQue},
  mixins: [editAndAdd],
  data() {
    const numberValid = {type: "number", message: "请输入数字！"};
    const dataStruct = {
      endtime: "",
      isenabled: true,
      isprivate: false,
      israndom: "false",
      isstusame: true,
      minutes: 0,
      multiplechoicecount: null,
      multiplechoicescore: 2,
      multiplequelist: [],
      paperid: null,
      papername: "",
      papertype: null,
      quebanklist: [],
      quelist: "",
      scorestandard: [
        {Standard: "不及格", StartScore: 0, EndScore: 59.99},
        {Standard: "及格", StartScore: 60, EndScore: 79.99},
        {Standard: "良好", StartScore: 80, EndScore: 89.99},
        {Standard: "优秀", StartScore: 90, EndScore: 100}
      ],
      singlechoicecount: null,
      singlechoicescore: 1,
      singlequelist: [],
      starttime: "",
      sublist: [],
      subquedetails: [],
      totalquecount: 0,
      truefalsecount: null,
      truefalsequelist: [],
      truefalsescore: 1,
      chapteridlist: [],
      //辅助字段
      selectTime: []
    };
    return {
      moduleName: "试卷",
      dataStruct,
      singleData: this.deepClone(dataStruct),
      paperType,
      steps: ["填写基本信息", "设置试卷题目", "设置分值标准"],
      requiredAndNumber: [
        {required: true, message: "该项为必填项！"},
        numberValid
      ],
      queListKey: {
        1: {
          count: "singlechoicecount",
          list: "singlequelist"
        },
        2: {
          count: "multiplechoicecount",
          list: "multiplequelist"
        },
        3: {
          count: "truefalsecount",
          list: "truefalsequelist"
        }
      },
      step: 0,
      queBanks: [],
      subjects: [],
      chapters: [],
      showSelectQueDialog: false,
      rules: {
        papername: {required: true, message: "请输入试卷名！"},
        papertype: {required: true, message: "请选择试卷类型！"},
        selectTime: {required: true, message: "请选择试卷有效时间！"},
        quebanklist: {required: true, message: "请选择题库！"},
        sublist: {required: true, message: "请选择科目！"},
        singlechoicescore: [
          {required: true, message: "请输入单选题每题分数！"}
        ]
      },
      timeRule:{
        selectTime: {required: false, message: "请选择试卷有效时间！"},
      },
      stepRule: [
        ["papername", "papertype", "selectTime"],
        ["quebanklist", "chapteridlist", "sublist"]
      ]
    };
  },
  watch: {
    "singleData.papertype"(){
       this.rules.selectTime.required=this.singleData.papertype == 1? false:true
    },
    "singleData.sublist"(n) {
			
			this.singleData.multiplequelist=[];//当科目变动，章节为空需重新选择
      const {subquedetails} = this.singleData;
      if (n.length === subquedetails.length) return;
      if (n.length > subquedetails.length) {
        //add selected subject
        const {subId} = JSON.parse(n[n.length - 1]);
        const result = JSON.parse(n[n.length - 1]);
        this.singleData.subquedetails.push({
          MultipleChoiceCount: 0,
          SingleChoiceCount: 0,
          SubId: result.subid,
          TrueFalseCount: 0,
          name: result.name
        });
      } else {
        //delete subject 将新旧数据进行比对，找出已删除元素
        for (let i = 0; i < subquedetails.length; i++) {
          const queDetail = subquedetails[i];
          for (var j = 0; j < n.length; j++) {
            const item = JSON.parse(n[j]);
            if (item.subid == queDetail.SubId) break;
          }
          if (j === n.length) this.singleData.subquedetails.splice(i, 1);
        }
      }
    }
  },
  created() {
    this.api.getUserQueBank.apply(this);
  },
  methods: {
    handle() {
      let singleData = this.deepClone(this.singleData);
      if (singleData.israndom === "true") {
        //随机试题
        this.setQueCount();
        singleData.chapteridlist = singleData.chapteridlist.join(",");
      } else {
        //固定试题
        singleData.quelist = [
          singleData.singlequelist,
          singleData.truefalsequelist,
          singleData.multiplequelist
        ].join(",");
        singleData.chapteridlist = "";
      }
      for (const key in this.queListKey) {
        const {list, count} = this.queListKey[key];
        if (singleData.israndom === "false")
          singleData[count] += singleData[list].length;
        singleData[list] = singleData[list].join(",");
        singleData.totalquecount += singleData[count];
      }
      singleData.sublist = singleData.sublist
          .map(item => JSON.parse(item).subid)
          .join(",");
      singleData.quebanklist = singleData.quebanklist.join(",");
      singleData.scorestandard = JSON.stringify(singleData.scorestandard);
      return this.axios.post("/sys/papermanage/addAndUpdatePaper", singleData);
    },
    checkFields(step, callback) {
      let validFieldsNum = 0;
      //form 表单字段校验
      this.$refs.form.validateField(this.stepRule[step], valid => {
        if (valid) {
          callback(false);
          return false;
        } else validFieldsNum++;
      });
      //额外字段校验
      this.validStep(step).then(res => {
        callback(validFieldsNum === this.stepRule[step].length && res);
      });
    },
    handleClick(val) {
      //切换固定/随机试题tab时，清空数据 【弃用】
      if (this.singleData.israndom == "true") {
        this.singleData.subquedetails = [];
        this.singleData.sublist.forEach(item => {
          const result = JSON.parse(item);
          this.singleData.subquedetails.push({
            MultipleChoiceCount: 0,
            SingleChoiceCount: 0,
            TrueFalseCount: 0,
            SubId: result.subid,
            name: result.name
          });
        });
      }
    },
    setQueCount() {
      //将随机试题的题目数量，提取到singleData中
      const queListKey = this.queListKey;
      for (let i = 0; i < this.singleData.subquedetails.length; i++) {
        const {
          singleChoiceCount,
          multipleChoiceCount,
          trueFalseCount
        } = this.singleData.subquedetails[i];
        this.singleData[queListKey["1"].count] += singleChoiceCount;
        this.singleData[queListKey["2"].count] += multipleChoiceCount;
        this.singleData[queListKey["3"].count] += trueFalseCount;
      }
    },
    async validStep(step) {
      if (step === 0) return true;
      const queListKey = this.queListKey;
      const singleData = this.singleData;
      //验证题目数量
      const res = await this.verifyQueCount();
      if (!res) return false;
      if (step === 1) {
        this.setQueCount();
        let queTotal = 0;
        // let validScore = 0;
        if (this.singleData.israndom === "false") {
          //固定试题 题目数量校验
          for (const key in queListKey) {
            const {list} = queListKey[key];
            queTotal += singleData[list].length;
          }
        } else {
          for (let i = 0; i < this.singleData.subquedetails.length; i++) {
            //计算随机试题中，每个科目下的每种题型的数量总和
            const item = this.singleData.subquedetails[i];
            queTotal += Object.keys(item)
                .filter(key => key.includes("Count"))
                .reduce((total, key) => {
                  total += isNaN(item[key]) ? 0 : item[key];
                  return total;
                }, 0);
          }
        }
        if (queTotal === 0) {
          const str = this.singleData.israndom === "false" ? "选择" : "输入";
          this.$message.error(`题目数量为0！请${str}题目！`);
          return false;
        }
      }
      return true;
    },
    onQueBankChange(queBanks) {
      const queBankIds = queBanks.join(",");
      this.emptySubject();
      this.api.getSubjectsOfQueBank.apply(this, [queBankIds]);
    },
    onSubjectChange(e) {
      this.emptyChapter();
      this.api.getGroupChapter.apply(this, [
        e.map(item => JSON.parse(item).subid).join(",")
      ]);
    },
    emptyQueBank() {
      this.singleData.quebanklist.splice(0);
      this.emptySubject();
    },
    emptySubject() {
      this.singleData.sublist.splice(0);
      this.emptyChapter();
    },
    emptyChapter() {
      this.singleData.chapteridlist.splice(0);
    },
    onSelectQue(queType) {
			if(this.singleData.sublist.length==0){
				this.$alert('请选择科目后，再选择题目', '提示', {
				          confirmButtonText: '确定'
			  });
				return
			}
      const selectQueDialog = this.$refs.selectQue;
      const dialogData = selectQueDialog.$data;
      const {singleData, queListKey} = this;
      const {list} = queListKey[queType];
      this.showSelectQueDialog = true;
      dialogData.subjects = singleData.sublist.map(sub => JSON.parse(sub));
      dialogData.selectedQue = singleData[list];
      dialogData.apiSetting.data.qustypeid = queType;
    },
    getSubName(subId) {
      return this.subjects.filter(item => item.subid == subId)[0].name;
    },
    verifyQueCount() {
      //随机试题时验证用户输入题目数量是否超出真实题目数量
      const {chapteridlist, subquedetails} = this.singleData;
      return new Promise((resolve, reject) => {
        this.axios
            .post("/sys/papermanage/judgmentCountExist", {
              chapteridlist: chapteridlist === '' ? chapteridlist : chapteridlist.join(","),
              subquedetails,
              israndom: this.singleData.israndom
            })
            .then(() => resolve(true))
            .catch(() => resolve(false));
      });
    },
    addQue(queList, queTypeId) {
      this.singleData[this.queListKey[queTypeId].list] = queList;
    },
    onClosed() {
      this.step = 0;
      this.singleData = this.deepClone(this.dataStruct);
      this.subjects.splice(0);
      this.end();
    }
  }
};
</script>

<style scoped>
.el-form {
  width: 750px;
  margin: 0 auto;
}

.el-form >>> .el-input {
  width: 220px;
}

.el-form >>> .el-select,
.el-form >>> .el-select .el-input {
  width: 350px;
}

.el-form >>> .el-input-number,
.el-form >>> .el-input-number .el-input {
  width: 150px;
}

.el-form-item-inline >>> .el-form-item__content {
  display: flex;
  flex-wrap: wrap;
  width: calc(100% - 110px);
}

.el-form-item-inline >>> .el-form-item__content > * {
  width: 30%;
  margin-right: 10px;
}

.step:nth-child(1),
.step:nth-child(3) {
  width: 500px;
  margin-left: auto;
  margin-right: auto;
}
</style>
